package com.pang.springcloud.controller;

import com.pang.springcloud.dao.PaymentDao;
import com.pang.springcloud.entities.CommonResult;
import com.pang.springcloud.entities.Payment;
import com.pang.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @author： pang-yun
 * @date： 2022-02-08 11:03
 * Description:
 */
@RestController
@Slf4j
public class PaymentController {

    @Autowired
    private PaymentService paymentService;


    @Value("${server.port}")
    private String serverPort;

    //如果发送的JSON数据是一个类中的不同属性，在Controller方法中使用@RequestBody会直接封装进该类中
    @PostMapping("/payment/add")
    public CommonResult add(@RequestBody Payment payment) {
        int result = paymentService.add(payment);
        log.info("------result " + result);
        if (result > 0) {
            return new CommonResult(200, "插入数据成功 + serverPort: "+serverPort, result);
        } else {
            return new CommonResult(400, "插入失败");
        }
    }


    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        Payment paymentById = paymentService.getPaymentById(id);
        log.info("-----查询+ " + " s");
        if (paymentById != null) {
            return new CommonResult<Payment>(200, "查询数据成功 + serverPort: "+serverPort, paymentById);
        } else {
            return new CommonResult(400, "查询失败");
        }
    }


    @Autowired
    private PaymentDao paymentDao;

    @GetMapping("/payment/test")
    public CommonResult<Payment> getPayment() {
        Payment payment = paymentDao.getPayment(1L, "一");
        return new CommonResult<>(200, "success", payment);
    }


    @GetMapping("/payment/loadBalances")
    public String getPaymentLoadBalances(){
        return serverPort;
    }


    //进行OpenFeign 超时测试
    @GetMapping("/payment/timeout")
    public String getServerPortTimeout() throws InterruptedException {
        TimeUnit.SECONDS.sleep(5);
        return serverPort;
    }
}
